package yxy.apple.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeUtility {

	static public UnicodeSet UNICODE_BasicLatin = new UnicodeSet("\\u0020-\\u007E");// 基本拉丁字母
	static public UnicodeSet UNICODE_BasicLatinNumeric = new UnicodeSet("\\u0030-\\u0039");// 基本拉丁字母 数字
	static public UnicodeSet UNICODE_BasicLatinUpperCase = new UnicodeSet("\\u0041-\\u005A");// 基本拉丁字母 大写
	static public UnicodeSet UNICODE_BasicLatinLowerCase = new UnicodeSet("\\u0061-\\u007A");// 基本拉丁字母 小写
	static public UnicodeSet UNICODE_Hiragana = new UnicodeSet("\\u3041-\\u3093\\u309B-\\u309E");// 平假名
	static public UnicodeSet UNICODE_Katakana = new UnicodeSet("\\u30A1-\\u30F6\\u30FC-\\u30FE");// 片假名
	static public UnicodeSet UNICODE_Bopomofo = new UnicodeSet("\\u3105-\\u3129");// 注音符号
	static public UnicodeSet UNICODE_CJKUnifiedIdeographsExtensionA = new UnicodeSet("\\u3400-\\u4DB5");// 中日韩统一表意文字扩展区A
	static public UnicodeSet UNICODE_CJKUnifiedIdeographs = new UnicodeSet("\\u4E00-\\u9FA5");// 中日韩统一表意文字

	static public UnicodeSet UnicodeSet_Name = new UnicodeSet(UNICODE_BasicLatinNumeric, UNICODE_BasicLatinUpperCase, UNICODE_BasicLatinLowerCase,
			UNICODE_Hiragana, UNICODE_Katakana, UNICODE_CJKUnifiedIdeographsExtensionA, UNICODE_CJKUnifiedIdeographs);

	static public UnicodeSet UnicodeSet_Chat = new UnicodeSet(UNICODE_BasicLatin, UNICODE_BasicLatinUpperCase, UNICODE_BasicLatinLowerCase, UNICODE_Hiragana,
			UNICODE_Katakana, UNICODE_CJKUnifiedIdeographsExtensionA, UNICODE_CJKUnifiedIdeographs);

	/** 用正则表达式表示字符范围 */
	static public class UnicodeSet {
		private String regex;

		public UnicodeSet(UnicodeSet... sets) {
			StringBuffer sb = new StringBuffer();
			for (UnicodeSet set : sets) {
				sb.append(set.getRegex());
			}
			regex = sb.toString();
		}

		public UnicodeSet(String regex) {
			this.regex = regex;
		}

		public String getRegex() {
			return regex;
		}
	}

	static public String trimUnicode(String text, UnicodeSet... sets) {
		UnicodeSet set = new UnicodeSet(sets);
		return trimUnicode(text, set);
	}

	static public String trimUnicode(String text, UnicodeSet set) {
		String regex = String.format("[^%s]+", set.getRegex());
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(text);
		return matcher.replaceAll("?");
	}

	static public boolean checkUnicode(String text, UnicodeSet... sets) {
		UnicodeSet set = new UnicodeSet(sets);
		return checkUnicode(text, set);
	}

	static public boolean checkUnicode(String text, UnicodeSet set) {
		String regex = String.format("[%s]", set.getRegex());
		Pattern pattern = Pattern.compile(regex);
		for (int i = 0; i < text.length(); i++) {
			String temp = String.valueOf(text.charAt(i));
			Matcher matcher = pattern.matcher(temp);
			if (!matcher.find()) {
				return false;
			}
		}
		return true;
	}
}
